package com.foreveredu.erlms.web.struts.action;

import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;

import com.foreveredu.erlms.domain.Department;
import com.foreveredu.erlms.domain.Examinee;
import com.foreveredu.erlms.domain.Grade;
import com.foreveredu.erlms.domain.PageModel;
import com.foreveredu.erlms.domain.Parameter;
import com.foreveredu.erlms.service.IExamService;
import com.foreveredu.erlms.service.IManagementService;
import com.linuxense.javadbf.DBFReader;

public class GradeAdminAction extends AbstractBaseDispatchAction {

	private IExamService examService = null;

	public IExamService getExamService() {
		return examService;
	}

	public void setExamService(IExamService examService) {
		this.examService = examService;
	}
	
	private IManagementService managementService = null;

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}
	
	//上传考试成绩表
	@SuppressWarnings("unchecked")
	public ActionForward fileGradeDBF(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 获得当前考试届次
		int examOrder = examService.getExamOrderOfNow();

		// 将考生成绩表保存到gradeDBF文件夹中
		String dirPath = request.getSession().getServletContext()
				.getRealPath("/gradeDBF");

		// 判断路径是否存在，如果不存在，就创建这个路径
		File fileDir = new File(dirPath);
		if (!fileDir.exists()) {
			fileDir.mkdir();
		}

		Hashtable<Object, Object> files = form.getMultipartRequestHandler()
				.getFileElements();

		String gradeDBF = null;

		for (Enumeration<Object> e = files.keys(); e.hasMoreElements();) {
			String key = (String) e.nextElement();

			try {
				FormFile formFile = (FormFile) files.get(key);
				String fileName = formFile.getFileName().trim();// 获得待上传的文件名

				if (fileName == null || fileName.equals("")) {
					request.setAttribute("fileGradeDBFEmptyError", "上传的DBF文件为空！");
					return mapping.findForward("fileGradeDBF");
				}

				// 获得当天日期
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String datetime = sdf.format(date);
				// 保存后的文件名不能使用原来的,可以防止下载出错
				// 新文件名为当前
				String newFileName = datetime + examOrder;

				// 读出原文件的扩展名
				String ext = "";
				int pos = fileName.lastIndexOf(".");
				ext = fileName.substring(pos);// 得到扩展名

				if (!ext.equalsIgnoreCase(".DBF")) {
					request.setAttribute("fileGradeDBFFormatError", "文件格式不对，只能是DBF格式！");
					return mapping.findForward("fileGradeDBF");
				}

				// 拼出完整的新文件名
				// newFileName = datetime + newFileName +
				// ext;//暂时先将报名号作为上传相片的文件名
				newFileName = newFileName + ext;
				gradeDBF = newFileName;

				InputStream is = formFile.getInputStream();
				OutputStream os = new FileOutputStream(dirPath
						+ File.separatorChar + newFileName);

				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = is.read(buffer)) != -1) {
					os.write(buffer, 0, bytesRead);
				}
				os.flush();

				is.close();
				os.close();

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		String path = dirPath + "\\" + gradeDBF;

		InputStream fis = null;
		try {
			fis = new FileInputStream(path);
			DBFReader reader = new DBFReader(fis);
			reader.setCharactersetName("GBK");

			// 从DBF文件中读取报名号，通过报名号查找到相应的考生，将其准考证号修改为DBF文件中相应的准考证号
			Object[] rowValues = null;
			while ((rowValues = reader.nextRecord()) != null) {
				Examinee examinee = examService.findExamineeByTicketNumber((String) rowValues[0],examService.getExamOrderOfNow());
				if(examinee != null){
				Grade grade = new Grade();
				grade.setExaminee(examinee);
				grade.setZcj((Double)rowValues[8]);
				grade.setZsbh((String)rowValues[9]);
				grade.setZzbscj((Double)rowValues[3]);
				grade.setZzsjcj((Double)rowValues[6]);
				if(examService.findGradeByExamineeId(grade.getExaminee().getId()) != null){
					request.setAttribute("fileGradeDBFError", "该数据表已经导入到数据库中，请勿重复导入");
					return mapping.findForward("fileGradeDBF");
				}
				examService.saveGrade(grade);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		request.setAttribute("fileGradeDBFSuccess", "导入数据成功");
		return mapping.findForward("fileGradeDBF");
	}
	
	//后台考生信息翻页列表
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 获取当前考次
		int examOrder = examService.getExamOrderOfNow();

		int offset = 0;
		String pageOffset = request.getParameter("pager.offset");// 获得翻页参数，即下一开始的纪录位置
		if (pageOffset != null && !pageOffset.equals("")) {
			offset = Integer.parseInt(pageOffset);
		}
		if (offset < 0) {
			return mapping.findForward("gardeList");
		}
		PageModel pm = examService.findGradeList(offset, examOrder);
		request.setAttribute("pm", pm);
		return mapping.findForward("gardeList");
	}
	//成绩分析图
	public ActionForward gradeImg(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//获取所有的考次列表
		List<Integer> examOrderList = new ArrayList<Integer>();
		List<Parameter> parameters = new ArrayList<Parameter>();
		examOrderList = examService.findExamOrderByExaminee();
		
		for(Iterator<Integer> examOrder =examOrderList.iterator(); examOrder.hasNext();){
			Parameter parameter =new Parameter();
			parameter.setExamOrder(examOrder.next());
			parameters.add(parameter);
		}
		
		request.setAttribute("parameters", parameters);
		
		// 获取当前考次
		int examOrder = examService.getExamOrderOfNow();
		
		List<Department> deptList = managementService.findDepartments();		

		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		
		for (Iterator<Department> departments = deptList.iterator();departments.hasNext();) {
			Department department =departments.next();
			//查找出该院系下不及格学生人数
			int gradeOverNum = examService.findGradeByDeptIdAndZcj(department.getId(),examOrder);
			int gradeAllNum = examService.findGradeByDeptId(department.getId(),examOrder);
			if(gradeAllNum == 0){
				dataset.addValue(0, "", department.getDeptName());
			}else{
				int gradeScale=(int)(((gradeAllNum - gradeOverNum)/(double)gradeAllNum)*100);
				dataset.addValue(gradeScale, "", department.getDeptName());
			}
		}
		
		JFreeChart chart = ChartFactory.createBarChart3D("各院系过级比例图", " ",
				"过级率百分比", dataset, PlotOrientation.VERTICAL, false, false,
				false);
		CategoryPlot plot=chart.getCategoryPlot();
		ValueAxis rangeAxis=plot.getRangeAxis();//获取柱状  
		rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,20));  

//		chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));
		//设置标题字体
		chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));
		
//		chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);

		
		BarRenderer3D renderer = new BarRenderer3D();
		renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); 
		renderer.setBaseItemLabelsVisible(true); 
		renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); 
		renderer.setItemLabelAnchorOffset(10D); 
		plot.setRenderer(renderer); 
		
		CategoryAxis domainAxis = plot.getDomainAxis();  
		domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,11));// X轴字体    

		
		String filename = ServletUtilities.saveChartAsPNG(chart,1000,520,null);
		String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename;
		request.setAttribute("filename", filename);
		request.setAttribute("graphURL", graphURL);
		return mapping.findForward("gradeImg");
	}
}
